<?php

class Sistema_ProfessorController extends App_Controller_Action
{
    
    private $_table     = 'PROFESSOR';
    private $_pk        = 'PRS_ID';
    private $_order_col = 'PRS_NOM';
    private $_order     = 'ASC';
    private $_sta_col   = 'PRS_STA';
    private $obj        = '';
    private $form       = '';
    public  $dir        = 'public/upload//';
    public  $_file_col  = 'PRS_FILE';
    
    public function init()
    {
        if($this->getRequest()->getActionName() == 'edit') $this->form = new Sistema_Form_Professor();
    }

    public function indexAction() {
        
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('elemform','library');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_list.js');
        
        $where = $this->_pk.' > 0';
        
        $stafiltro = $this->_getParam('stafiltro', '1'); 
        if($stafiltro != '') $where .= ' AND PRS_STA = ' . $stafiltro;
        $this->view->stafiltro  = $stafiltro;
        
        $itfiltro = $this->_getParam('itfiltro', ''); 
        if($itfiltro != '') $where .= ' AND PRS_NOM like "' . $itfiltro.'%"';
        $this->view->itfiltro = $itfiltro; 
        
        
        $query = 'SELECT SQL_CACHE p.*, d.DCP_NOM FROM '.$this->_table.' p, DISCIPLINA d WHERE p.DCP_ID = d.DCP_ID AND '.$where.' ORDER BY '.$this->_order_col.' '.$this->_order.'';
        $result = $this->db->fetchAll($query);
        $this->view->result = $this->paginacao($result);
        
        $this->view->cbs_id = $cbs_id;
        
    }
    
    
    public function editAction() {
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskMoney.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskedinput.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/mask.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        $this->view->headLink()->prependStylesheet($this->_urlbase.'/public/media/js/chosen/chosen.min.css'); 
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/chosen/chosen.jquery.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_professor.js?1=20'); 
        
       
        $this->view->form = $this->form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                if($this->form->isValid($formData)) {
                    $id = (int) $this->form->getValue($this->_pk);

                    $data = $this->form->getValues();
                    
                    unset($data['PRS_LOG']);
                    unset($data['PRS_SNH']);
                    unset($data['PRS_SNH2']);
                    unset($data['CBS_IDS']);
                    unset($data['CUR_IDS']);
                    //print_r($formData);exit();
                    $data['CBS_ID'] = isset($formData['CBS_ID']) ? implode(',', $formData['CBS_ID']).',0':'';
                    $data['CUR_ID'] = isset($formData['CUR_ID']) ? implode(',', $formData['CUR_ID']).',0':'';
                    
                    if ($id == 0){
                        
                        // inserir usuário para aluno
                        $user = array(
                            'USU_LOGIN'     => $formData['PRS_LOG'],	
                            //'USU_SENHA'     => sha1($form->getValue('USU_SENHA')),	
                            'USU_NOME'      => $formData['PRS_NOM'],	
                            'PER_ID'        => 7, // permissão professores
                            'USU_DTCADASTRO'=> date('Y-m-d'),
                            //'USU_TPO'       => 3, 
                            'TUS_ID'        => 3,
                            'USU_CADSTA'    => 1,
                            'USU_STA'       => 1,  
                            'USU_EMAIL'     => $data['PRS_EML'],
                        );
                        if(strlen($formData['PRS_SNH']) > 1){
                            $user['USU_SENHA'] = sha1($formData['PRS_SNH']);
                        }
                        $this->db->insert('USUARIOS',$user);
                        $USU_ID =  $this->db->lastInsertId();
                        
                        $data['USU_ID'] = $USU_ID;
                        
                        $this->db->insert($this->_table,$data);
                    
                    }else{
                        
                        if(strlen($formData['PRS_SNH']) > 1){
                            $user = array('USU_SENHA' => sha1($formData['PRS_SNH']) );
                            $this->db->update('USUARIOS',$user,'USU_ID = '.$data['USU_ID']);
                        }
                                               
                        $this->db->update($this->_table,$data, $this->_pk.' = ' . $id);
                    }

                    $this->_helper->redirector('index');      
                } else {
                    $this->form->populate($formData);
                }
            } catch(Exception $ex) {
                echo '<script>alert("'.$ex->getMessage().'");</script>';
                $this->form->populate($formData);
            }  
        } else {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $query = 'SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$this->_pk .' = ' . $id;
                $data = $this->db->fetchRow($query);
                
                $query = 'SELECT SQL_CACHE USU_LOGIN FROM USUARIOS WHERE USU_ID = ' . $data['USU_ID'];
                $user = $this->db->fetchRow($query);
                $data['PRS_LOG'] = $user['USU_LOGIN'];
                
                $this->form->populate($data);
                
            }
        }
    }

    public function deleteAction() {
        
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        
        $ok = FALSE;
        
        $id = $this->_getParam('id', 0);
        if ((int)$id > 0 ) {
            $data = array($this->_sta_col => 0);
            $ok = (bool) $this->db->update($this->_table,$data, $this->_pk .' = ' . $id);
            
            $query = 'SELECT SQL_CACHE USU_ID FROM '.$this->_table.' WHERE '.$this->_pk .' = ' . $id;
            $data = $this->db->fetchRow($query);
            
            $user = array('USU_STA' => 0);
            $ok = (bool) $this->db->update('USUARIOS',$user,'USU_ID = '.$data['USU_ID']);

        }
        
        echo json_encode(array('ok' => $ok));
    }
    
    public function gruposAction() {
        
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        
        $ok = TRUE;
        $html = '';
        $id = $this->_getParam('id', 0);
        $ids = $this->_getParam('ids', 0);
        $ids = $ids == 0 ? $ids:implode(',',$ids);
        //if((int)$ids > '' ) {          
            $query = 'SELECT SQL_CACHE CUR_ID FROM PROFESSOR WHERE PRS_ID = ' . $id;
            $data = $this->db->fetchRow($query);
            $arr_set = array();
            foreach(explode(',',$data['CUR_ID']) as $arr_ex) $arr_set[$arr_ex] = $arr_ex;
            
            $html = '<select id="CUR_ID[]" name="CUR_ID[]" class="chosen-select CUR_ID" multiple="multiple" style="width:500px;" '.$disabled.'>';
        
            $query = 'SELECT SQL_CACHE c.CUR_ID, t.NRT_NOM FROM CURSO c, NUMEROTURMA t  WHERE c.CBS_ID in('.$ids.') AND c.CUR_TRM = t.NRT_ID AND c.CUR_STA = 1 and c.CUR_ANO >= "'.date('Y').'"';
            $row = $this->db->fetchAll($query);
            foreach($row as $c){
                $selected = array_search($c['CUR_ID'], $arr_set) > '' ? 'selected=""':'';
                $html .= '<option '.$selected.' value="'.$c['CUR_ID'].'">'.$c['NRT_NOM'].'</option>'; 
            }
            $html .= '</select><script>$(function(){  $(".chosen-select").chosen(); });</script>';
        //}
        echo json_encode(array('ok' => $ok,'html'=>$html));
        
    }
    
}

